package com.example.demo.service.shoppingCart;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.constant.Status;
import com.example.demo.entity.shoppingCart.ShoppingCartInfo;
import com.example.demo.repository.shoppingCart.ShoppingCartInfoMapper;
import com.example.demo.service.shoppingCart.dto.ShoppingCartInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service


public class ShoppingCartService {

    @Autowired
    private ShoppingCartInfoMapper shoppingCartInfoMapper;

    public ShoppingCartInfo addtogoods(ShoppingCartInfoDto shoppingCartInfoDto) {
        ShoppingCartInfo shoppingCartInfo = shoppingCartInfoDto.dotoEntity();
        shoppingCartInfo.initEntity();
        Long time = System.currentTimeMillis();

        shoppingCartInfo.setCreateTime(time);
        shoppingCartInfo.setUpdateTime(time);

        int i = shoppingCartInfoMapper.insert(shoppingCartInfo);

        if (i <= 0) {
            return null;
        }
        return shoppingCartInfo;
    }

    public ShoppingCartInfo getshoppingCartInfoById(Long id) {
        LambdaQueryWrapper<ShoppingCartInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCartInfo::getIsDelete, Status.ENABLE)
                .eq(ShoppingCartInfo::getId, id);

        ShoppingCartInfo shoppingCartInfo = shoppingCartInfoMapper.selectOne(qw);

        return Objects.isNull(shoppingCartInfo) ? null : shoppingCartInfo;

    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteShoppingCart(Long id) {
        LambdaQueryWrapper<ShoppingCartInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCartInfo::getIsDelete, Status.ENABLE)
                .eq(ShoppingCartInfo::getId, id);

        ShoppingCartInfo shoppingCartInfo = shoppingCartInfoMapper.selectOne(qw);

        if (Objects.isNull(shoppingCartInfo)) {
            System.out.println("购物车不存在,id:" + id);
        }
        shoppingCartInfoMapper.deleteById(id);

        int i = shoppingCartInfoMapper.updateById(shoppingCartInfo);
        if (i <= 0) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
